<template>
    <div class="joblist-container">
        <!-- 编辑/发布职位弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑职位' : '发布职位'" width="70%">
            <el-form :model="jobForm" label-width="120px" :rules="rules" ref="jobFormRef">

                <el-form-item label="求人タイトル" prop="name">
                    <el-input v-model="jobForm.name" placeholder="请输入职位名称" />
                </el-form-item>
                <el-form-item label="募集人数" prop="recruits_people">
                    <el-input-number v-model="jobForm.recruits_people" :min="1" :max="100" />
                </el-form-item>
                <el-form-item label="給与制度" prop="salary_range">
                    <el-input v-model="jobForm.salary_range" placeholder="例如：50,000円〜950,000円" />
                </el-form-item>
                <el-form-item label="締切日" prop="limit_time">
                    <el-date-picker v-model="jobForm.limit_time" type="date" placeholder="締切日" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="仕事種類" prop="jobs_type_id">
                    <el-cascader
                        v-model="jobForm.jobs_type_id"
                        :options="jobTypes"
                        :props="{
                            value: 'jobs_type_id',
                            label: 'name',
                            children: 'child'
                        }"
                        placeholder="仕事種類"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="仕事内容" prop="content">
                    <div class="editor-container">
                      <Toolbar
                        style="border-bottom: 1px solid #ccc"
                        :editor="editorRef"
                        :defaultConfig="toolbarConfig"
                        :mode="mode"
                      />
                      <Editor
                        style="height: 300px; width: 100%; overflow-y: auto; white-space: pre-wrap;"
                        v-model="jobForm.content"
                        :defaultConfig="editorConfig"
                        :mode="mode"
                        @onCreated="handleCreated"
                      />
                    </div>
                </el-form-item>
                <el-form-item label="公開状態" prop="status">
                    <el-radio-group v-model="jobForm.status">
                        <el-radio :label="1">公開</el-radio>
                        <el-radio :label="2">非公開</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitJob" :loading="submitting">
                        {{ isEdit ? '更新' : '发布' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 顶部操作区 -->
        <div class="top-actions" v-if="isCompanyAccount">
            <el-button type="primary" @click="openDialog(false)">发布新职位</el-button>
        </div>

        <!-- 表格 -->
        <el-table :data="jobList" style="width: 100%; font-size: 12px;" border stripe v-loading="loading">
            <el-table-column prop="name" label="职位名称" width="200" />
            <el-table-column prop="jobs_type_id" label="职位类别" width="200">
                <template #default="scope">
                    {{ getJobTypeName(scope.row.jobs_type_id) }}
                </template>
            </el-table-column>
            <el-table-column prop="recruits_people" label="招聘人数" width="80" />
            <el-table-column prop="salary_range" label="薪资范围" width="180" />
            <el-table-column prop="limit_time" label="到期日期" width="120" />
            <el-table-column prop="createtime" label="创建时间" width="120" />
            <!-- <el-table-column prop="content" label="职位描述" show-overflow-tooltip /> -->
            <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                        {{ scope.row.status === 1 ? '开放' : '隐藏' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="140">
                <template #default="scope">
                    <div class="button-group">
                        <el-button type="primary" size="small" @click="openDialog(true, scope.row)">
                            编辑
                        </el-button>
                        <el-popconfirm title="确定要删除这个职位吗？" @confirm="deleteJob(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="sizes, prev, pager, next" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef, computed } from 'vue'
import { jobsApi } from '../../../api/index.js'
import { ElMessage, ElLoading } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 职位列表数据
const jobList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 编辑器配置
const toolbarConfig = {
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'bulletedList',
    'numberedList',
    'insertLink',
    'lineHeight',
    '|',
    'undo',
    'redo'
  ]
}

const editorConfig = {
  placeholder: '请输入职位描述...',
  MENU_CONF: {
    // 配置换行相关选项
    lineHeight: {
      lineHeightList: ['1', '1.5', '1.75', '2', '3', '4']
    },
    // 配置段落格式
    paragraphStyle: {
      textIndent: '2em'
    },
    // 配置回车换行行为
    enterToCreateP: {
      enabled: true
    }
  }
}

// 编辑器模式
const mode = 'default'

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器创建完成时的回调
const handleCreated = (editor) => {
  editorRef.value = editor
  
  // 设置编辑器内容处理函数
  try {
    const originalHtml = editor.getHtml()
    if (originalHtml) {
      // 确保内容中的换行符被正确处理
      const processedHtml = originalHtml.replace(/\n/g, '<br>')
      editor.setHtml(processedHtml)
    }
  } catch (error) {
    console.error('处理编辑器内容时出错:', error)
  }
}
const loading = ref(false)
const submitting = ref(false)

// 检查是否为公司账号（type=2）
const isCompanyAccount = computed(() => {
    // 从localStorage获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
        try {
            const userInfo = JSON.parse(userInfoStr)
            return userInfo.type === 2 // 公司账号类型为2
        } catch (error) {
            console.error('解析用户信息失败:', error)
            return false
        }
    }
    return false
})

// 职位类型数据
const jobTypes = ref([])

// 弹窗控制
const dialogVisible = ref(false)
const isEdit = ref(false)
const jobFormRef = ref(null)

// 表单数据
const jobForm = reactive({
    jobs_type_id: '',
    name: '',
    recruits_people: 1,
    salary_range: '',
    limit_time: '',
    content: '',
    status: 1,
    jobs_id: ''
})

// 表单验证规则
const rules = {
    jobs_type_id: [{ required: true, message: '请选择职位类别', trigger: 'change' }],
    name: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
    recruits_people: [{ required: true, message: '请输入招聘人数', trigger: 'blur' }],
    salary_range: [{ required: true, message: '请输入薪资范围', trigger: 'blur' }],
    limit_time: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
    content: [{ required: true, message: '请输入职位描述', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取职位类型
const getJobTypes = async () => {
    try {
        const res = await jobsApi.getJobsType()
        if (res.code === 1) {
            // 保留原始的两级结构
            jobTypes.value = res.data
        } else {
            ElMessage.error(res.msg || '获取职位类型失败')
        }
    } catch (error) {
        console.error('获取职位类型出错:', error)
        ElMessage.error('获取职位类型失败')
    }
}

// 获取职位列表
const getJobsList = async () => {
    loading.value = true
    try {
        const params = {
            page: currentPage.value,
            limit: pageSize.value
        }

        const res = await jobsApi.getJobsList(params)
        if (res.code === 1) {
            jobList.value = res.data.list
            total.value = parseInt(res.data.totalCount)
        } else {
            ElMessage.error(res.msg || '获取职位列表失败')
        }
    } catch (error) {
        console.error('获取职位列表出错:', error)
        ElMessage.error('获取职位列表失败')
    } finally {
        loading.value = false
    }
}

// 根据职位类型ID获取类型名称
const getJobTypeName = (typeId) => {
    // 遍历所有分类及其子分类
    for (const category of jobTypes.value) {
        if (category.child && category.child.length > 0) {
            const subType = category.child.find(item => item.jobs_type_id === typeId)
            if (subType) {
                return `${category.name} - ${subType.name}`
            }
        }
    }
    return '未知类型'
}

// 打开编辑/发布对话框
const openDialog = (edit, row) => {
    isEdit.value = edit
    dialogVisible.value = true

    // 重置表单
    Object.keys(jobForm).forEach(key => {
        if (key === 'recruits_people') {
            jobForm[key] = 1
        } else if (key === 'status') {
            jobForm[key] = 1
        } else {
            jobForm[key] = ''
        }
    })

    // 如果是编辑，填充表单数据
    if (edit && row) {
        Object.keys(jobForm).forEach(key => {
            if (key === 'jobs_id') {
                jobForm[key] = row.id
            } else if (key === 'jobs_type_id' && row[key] !== undefined) {
                // 为级联选择器找到正确的路径值 [父类ID, 子类ID]
                for (const categoryIndex in jobTypes.value) {
                    const category = jobTypes.value[categoryIndex];
                    if (category.child && category.child.length > 0) {
                        for (const childIndex in category.child) {
                            const subType = category.child[childIndex];
                            if (subType.jobs_type_id === row[key]) {
                                // 级联选择器需要的是数组格式 [子类ID]
                                jobForm[key] = row[key];
                                break;
                            }
                        }
                    }
                }
            } else if (row[key] !== undefined) {
                jobForm[key] = row[key]
            }
        })
    }
}

// 提交职位表单
const submitJob = async () => {
    if (!jobFormRef.value) return

    await jobFormRef.value.validate(async (valid) => {
        if (!valid) return

        submitting.value = true
        try {
            // 创建一个新对象用于提交，确保jobs_type_id是正确的值
            const submitData = { ...jobForm }
            
            // 确保jobs_type_id是一个有效的ID值
            if (typeof submitData.jobs_type_id !== 'number') {
                // 如果是级联选择器返回的数组，取最后一个值（子类ID）
                if (Array.isArray(submitData.jobs_type_id) && submitData.jobs_type_id.length > 0) {
                    submitData.jobs_type_id = submitData.jobs_type_id[submitData.jobs_type_id.length - 1]
                }
            }
            
            const res = await jobsApi.saveJob(submitData)
            if (res.code === 1) {
                ElMessage.success(isEdit.value ? '职位更新成功' : '职位发布成功')
                dialogVisible.value = false
                getJobsList() // 刷新列表
            } else {
                ElMessage.error(res.msg || (isEdit.value ? '职位更新失败' : '职位发布失败'))
            }
        } catch (error) {
            console.error('提交职位出错:', error)
            ElMessage.error(isEdit.value ? '职位更新失败' : '职位发布失败')
        } finally {
            submitting.value = false
        }
    })
}

// 删除职位
const deleteJob = async (jobId) => {
    loading.value = true
    try {
        const res = await jobsApi.deleteJob(jobId)
        if (res.code === 1) {
            ElMessage.success('职位删除成功')
            getJobsList() // 刷新列表
        } else {
            ElMessage.error(res.msg || '职位删除失败')
        }
    } catch (error) {
        console.error('删除职位出错:', error)
        ElMessage.error('职位删除失败')
    } finally {
        loading.value = false
    }
}

// 分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    getJobsList()
}

// 页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    getJobsList()
}

// 判断是否为企业账号已在上方通过computed实现

// 页面加载时获取数据
onMounted(() => {
    getJobTypes()
    getJobsList()
})
</script>

<style scoped>
.joblist-container {
    padding: 10px;
    max-width: 1200px;
    margin: 0 auto;
}

.top-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

/* 按钮组样式 */
.button-group {
    display: flex;
    gap: 5px;
}

/* 弹窗样式 */
.dialog-footer {
    display: flex;
    justify-content: center;
    width: 100%;
}

.editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  z-index: 100;
  width: 100%;
}

/* 确保编辑器内容区域正确处理换行 */
.w-e-text-container {
  white-space: pre-wrap !important;
  word-break: break-word !important;
}

.w-e-text p {
  margin: 10px 0;
  line-height: 1.5;
}

/* 增强编辑器换行支持 */
.w-e-text {
  white-space: pre-wrap !important;
  word-break: break-all !important;
}

.w-e-text br {
  display: block !important;
  content: "" !important;
  margin-top: 0.5em !important;
}

/* 强制段落换行 */
.w-e-text p {
  display: block !important;
  margin: 1em 0 !important;
  white-space: pre-wrap !important;
}

/* 确保编辑器内容区域正确显示换行 */
.w-e-text-container p, .w-e-text-container div {
  white-space: pre-wrap !important;
  word-wrap: break-word !important;
  margin-bottom: 1em !important;
}

/* 修复编辑器内容区域的换行问题 */
.w-e-text-container [contenteditable=true] {
  white-space: pre-wrap !important;
  word-wrap: break-word !important;
}
</style>